package com.platform.modules.wallet.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.platform.common.exception.BaseException;
import com.platform.common.shiro.ShiroUtils;
import com.platform.common.shiro.utils.Md5Utils;
import com.platform.modules.chat.domain.ChatUser;
import com.platform.modules.wallet.domain.Wallet;
import com.platform.modules.wallet.domain.WalletAccount;
import com.platform.modules.wallet.domain.WalletDailyBill;
import com.platform.modules.wallet.service.WalletAccountService;
import com.platform.modules.wallet.service.WalletDailyBillhService;
import com.platform.modules.wallet.service.WalletService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Component
public class TransferUtils {

    @Resource
    private WalletService walletService;
    @Resource
    private WalletDailyBillhService walletDailyBillhService;
    @Resource
    private WalletAccountService walletAccountService;

    public void verifySend(String content, Wallet wallet, ChatUser cu) {

        JSONObject json = JSONUtil.parseObj(content);

        String payPassword = json.getStr("payPassword");
        int amount = new BigDecimal(json.getStr("amount")).multiply(BigDecimal.valueOf(100)).intValue();
        payPassword = Md5Utils.credentials(payPassword, cu.getSalt());
        //TODO 交易密码以后开通
//        if (!StrUtil.equals(payPassword,wallet.getPayPassword())){
//            throw new BaseException("交易密码有误，请重试");
//        }
        if (wallet.getAmount().intValue() < amount) {
            throw new BaseException("失败：金额超出余额");
        }

        this.verifyAccount();
    }

    public void verifyAccount() {

        //校验资金安全
        Long userId = ShiroUtils.getUserId();
        verifyAccount(userId);
    }


    public void verifyAccount(Long userId) {

        //校验资金安全
        Wallet wallet = walletService.findById(userId);

//        WalletDailyBill lastOne = walletDailyBillhService.getLastOne(userId);

        List<WalletDailyBill> dailyBills = walletDailyBillhService.queryById(userId);
        int bill = dailyBills.stream().mapToInt(WalletDailyBill::getAmount).sum();

        List<WalletAccount> queryToday = walletAccountService.queryToday(userId);
        int today = queryToday.stream().mapToInt(WalletAccount::getAmount).sum();

        if (wallet.getAmount().intValue()
                + wallet.getBalance().intValue()
                - today
                - bill != 0) {
            throw new BaseException("账目金额校验出错");
        }
    }
}
